package com.lin.netty.chat.handler;

import com.lin.netty.chat.message.LoginRequestMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ClientStateChangeHandler extends ChannelInboundHandlerAdapter {
    AtomicBoolean EXIT = new AtomicBoolean(false);

    /**
     * 连接建立触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 模拟登录业务
        new Thread(() -> { // 创建独立线程，不然使nio worker线程阻塞住
            while (!EXIT.get()) {
                log.debug("模拟登录业务");
                Scanner console = new Scanner(System.in);
                System.out.println("请输入用户名：");
                String userName = console.nextLine();
                System.out.println("请输入密码：");
                String pwd = console.nextLine();

                ctx.channel().writeAndFlush(new LoginRequestMessage(userName, pwd));
            }
        }, "login-server").start();

    }

    /**
     * 连接断开触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("连接断开了");
        ctx.channel().close();
        System.exit(1);
    }

    /**
     * 在出现异常时触发
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}
